package cn.webwheel.tutorials.integration;

import cn.webwheel.utils.DefaultAction;
import cn.webwheel.utils.WebParam;

import javax.servlet.http.HttpSession;

/**
 * 通过继承DefaultAction类实现了Action接口
 */
public class ActGuess extends DefaultAction {

    private HttpSession session;
    private int num;

    public ActGuess(HttpSession session) {
        this.session = session;
    }

    @WebParam("num")
    public void setNum(int num) {
        this.num = num;
    }

    public Object execute() throws Exception {
        // 设置神秘数字
        Integer secret = (Integer) session.getAttribute("secret");
        if (secret == null) {
            secret = (int) (Math.random() * 9) + 1;
            session.setAttribute("secret", secret);
        }
        String msg;
        if (num < secret) {
            msg = "你猜小了~";
        } else if (num > secret) {
            msg = "你猜大了~";
        } else {
            msg = "你猜对了！";
        }
        // 得到PageIndex动作类并执行，相当于实现了动作链
        PageIndex page = get(PageIndex.class);
        page.setMessage(msg);
        page.setNum(num);
        return page.execute();
    }
}
